/**
 * @this
 *
 * @flow
 */

'use strict'
import React, {Component} from 'react'
import {StyleSheet, View, Text, Button, Keyboard, TextInput} from 'react-native'

import store from 'react-native-rxstorage'

export default class SwithDns extends Component {
  static navigationOptions = (a, b) => {
    b = b || {}
    const route = b.route || {}
    const right = () => {
      return (
        <Button
          title={'保存'}
          onPress={e => {
            const p = route.params || {}
            const save = p.save || null
            save && save()
          }}
        />
      )
    }
    return {
      headerTitle: '编辑域名地址',
      headerRight: right,
    }
  }

  constructor(props) {
    super(props)

    console.log('props=', props)
    const navParams = this.props.route.params || {}
    const url = navParams.url
    this.defaultUrl = url

    this.state = {
      url,
    }
  }

  componentDidMount() {
    this.props.navigation.setParams({
      save: this._save,
    })
  }

  setDiyUrl(diyUrl = '') {
    store.save('diyUrl', diyUrl || '')
  }

  _save = () => {
    const nav = this.props.navigation || {}
    const {url} = this.state

    Keyboard.dismiss()

    if (!url) {
      alert('地址为空')
      return
    }

    if (this.defaultUrl === url) {
      nav.goBack()
      return
    }

    this.setDiyUrl(url)

    const navParams = nav.state.params || {}
    const nullfunc = () => {}
    const callback = navParams.callback || nullfunc
    callback && callback()

    nav.goBack()
  }

  formatSpace = string => {
    if (!string) {
      return ''
    }
    return string.replace(/\s+/g, '')
  }

  render() {
    const {url} = this.state

    return (
      <View style={styles.container}>
        <Text style={{marginLeft: 10}}>{this.defaultUrl}</Text>
        <View style={styles.textInputView}>
          <TextInput
            style={styles.textInput}
            value={url}
            multiline={true}
            onChangeText={value => {
              this.setState({url: this.formatSpace(value)})
            }}
          />
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 30,
    backgroundColor: 'white',
  },
  textInputView: {
    marginTop: 5,
    borderWidth: 1,
    padding: 5,
    paddingHorizontal: 10,
    borderColor: '#D3D3D3',
  },
  textInput: {
    padding: 0,
  },
})
